/**
 * Copyright (c) 2015-2018, Golly Hu 胡高 (3722711@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.hg.base.kit;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.util.ClassUtils;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * @author Golly
 *
 */
public class ClassLoadKit {
	private static final String RESOURCE_PATTERN = "/**/*.class";

	private static ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();

	@SafeVarargs
	public static Set<Class<?>> getClassSet(String[] basePackages, Class<?> ancestorClass,
											Class<? extends Annotation>... annotationFilter) throws IOException, ClassNotFoundException {

		Set<Class<?>> classSet = new HashSet<Class<?>>();

		List<TypeFilter> typeFilters = new LinkedList<TypeFilter>();

		if (annotationFilter != null) {
			for (Class<? extends Annotation> annotation : annotationFilter) {
				typeFilters.add(new AnnotationTypeFilter(annotation, false));
			}
		}

		for (String pkg : basePackages) {
			String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
					+ ClassUtils.convertClassNameToResourcePath(pkg) + RESOURCE_PATTERN;

			Resource[] resources = ClassLoadKit.resourcePatternResolver.getResources(pattern);
			MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(resourcePatternResolver);
			for (Resource resource : resources) {
				if (resource.isReadable()) {
					MetadataReader reader = readerFactory.getMetadataReader(resource);
					String className = reader.getClassMetadata().getClassName();
					if (matchesEntityTypeFilter(reader, readerFactory, typeFilters)) {
						Class<?> clazz = Class.forName(className);
						if (ancestorClass != null && ancestorClass.isAssignableFrom(clazz)) {
							classSet.add(clazz);
						} else if (ancestorClass == null) {
							classSet.add(clazz);
						}
					}
				}
			}
		}

		return classSet;
	}

	/**
	 * 检查当前扫描到的Bean含有任何一个指定的注解标记
	 *
	 * @param reader
	 * @param readerFactory
	 * @param typeFilters
	 * @return
	 * @throws IOException
	 */
	private static boolean matchesEntityTypeFilter(MetadataReader reader, MetadataReaderFactory readerFactory,
												   List<TypeFilter> typeFilters) throws IOException {
		if (!typeFilters.isEmpty()) {
			for (TypeFilter filter : typeFilters) {
				if (filter.match(reader, readerFactory)) {
					return true;
				}
			}
			return false;
		}
		return true;
	}
}
